package com.namecard.namecardapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.namecard.namecardapi.entity.TComment;
import com.namecard.namecardapi.entity.TCommodity;
import com.namecard.namecardapi.entity.vo.TCommodityVo;
import com.namecard.namecardapi.mapper.TCommentMapper;
import com.namecard.namecardapi.mapper.TCommodityMapper;
import com.namecard.namecardapi.service.TCommodityService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zm
 * @since 2024-04-21
 */
@Service
public class TCommodityServiceImpl extends ServiceImpl<TCommodityMapper, TCommodity> implements TCommodityService {
    @Resource
    private TCommodityMapper tCommodityMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private TCommentMapper tCommentMapper;

    @Override
    public IPage<TCommodity> selectAll(Page<TCommodity> pageParam, TCommodityVo commodityVo) {
        IPage<TCommodity> sysCommodityIPage = tCommodityMapper.selectCdPage(pageParam, commodityVo);
        return sysCommodityIPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delectById(Long id) {
        tCommodityMapper.delectById(id);
        //同时删除商品评论
        UpdateWrapper<TComment> wrapper = new UpdateWrapper();
        wrapper.set("is_deleted",1).eq("commodity_id",id);
        tCommentMapper.update(null,wrapper);
    }

    @Override
    public void updateByState(TCommodity tCommodity) {
        tCommodityMapper.updateByState(tCommodity);
    }

    @Override
    public void updateByRoll(TCommodity tCommodity) {
        tCommodityMapper.updateByRoll(tCommodity);
    }

    @Override
    public int insertCommdity(TCommodity tCommodity) {
       return tCommodityMapper.insertCommdity(tCommodity);

    }

    //通过id获取商品信息,设置浏览量
    //        redisTemplate.opsForValue().set(customUser.getUsername(), JSON.toJSONString(customUser.getAuthorities()));
//        String authoritiesString = (String) redisTemplate.opsForValue().get(useruame);
//        List<Map> mapList = JSON.parseArray(authoritiesString, Map.class);
    @Override
    public TCommodity getInfoById(Long id) {
        TCommodity commodity = tCommodityMapper.selectById(id);
        //获取浏览量
        Long pageView = commodity.getPageView();
        pageView = pageView+1;
        redisTemplate.opsForValue().set("pageView", pageView);
        //TODO 写一个30秒定时器，把缓存中的pageView放入放入数据库
        return null;
    }

}
